<template>
  <div class="d_content">
    <div class="d_content_childer">
      <div class="avatar">
        <img :src="userInfo.avatar?userInfo.avatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt=""
             style="width: 200px;height: 200px;border-radius: 50%"
             @error="handleImageError"
        >
      </div>
      <div class="descriptions">
        <el-descriptions title="其他用户基本信息" :column="1" border>
          <el-descriptions-item label="用户名">{{userInfo.username}}</el-descriptions-item>
          <el-descriptions-item label="邮箱"><span v-html="emailDisplay"></span></el-descriptions-item>
          <el-descriptions-item label="创建时间">{{formatData}}</el-descriptions-item>
          <el-descriptions-item label="角色">{{userInfo.role==="admin"? "管理员":(userInfo.role==="student"?"学生":"老师")}}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="button">
        <el-button type="primary" @click="updateInfo">修改用户信息</el-button>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogVisible">
    <el-form :model="userInfo" :rules="rules" ref="formRef" label-width="auto" style="max-width: 100%">
      <el-form-item label="头像" prop="avatar">
        <el-input v-model="userInfo.avatar" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userInfo.username" clearable></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userInfo.email" clearable></el-input>
      </el-form-item>
      <el-form-item label="修改密码" prop="password">
        <el-input type="password" v-model="userInfo.password" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button style="width: 100%;" type="primary" @click="confirm">修改</el-button>
      </el-form-item>
      <el-form-item>
        <el-button style="width: 100%;" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import {ref,reactive,onMounted,computed} from 'vue'
import {Update,GetUserId} from '../../api/user.js'
import dayjs  from 'dayjs'
import {useRouter} from 'vue-router'
import {ElLoading, ElMessage} from "element-plus";

const router = useRouter()
const dialogVisible = ref(false)
const userInfo = ref({
  account: "",
  avatar: "",
  createdAt:"",
  email:"",
  isDeleted:'',
  password:"",
  role:"",
  userId:'',
  username:""
})
const formRef = ref(null);



// 表单验证规则
const rules = reactive({
  avatar: [
    { required: false, message: "请输入头像链接", trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 1, max: 15, message: "用户名长度应在 1 到 15 个字符之间", trigger: "blur" },
  ],
  email: [
    { required: false, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度至少为 6 位", trigger: "blur" },
  ]
})
const updateInfo = ()=>{
  dialogVisible.value = true
}
const logout = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在登出...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  localStorage.removeItem('userInfo')
  localStorage.removeItem('token')
  localStorage.removeItem('r_vuex')
  await sleep(3000)
  router.push('/login')
  loadingInstance.close();
  ElMessage.success("请重新登录账号!");
}
const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}
const confirm = ()=>{
  dialogVisible.value = false
  formRef.value.validate((valid) => {
    if (valid) {
      // 表单验证通过后的逻辑
      Update(userInfo.value).then(res => {
        GetUserId(userInfo.value.userId).then(res => {
          localStorage.setItem('userInfo', JSON.stringify(res.data))
        })
      })
      ElMessage.success("修改成功！");
      logout()
    } else {
      ElMessage.error("表单验证失败，请检查输入内容！");
      return false;
    }
  })
}
const emailDisplay = computed(()=>{
  return userInfo.value.email != null ? userInfo.value.email : '<p style="color: #f1f4f6">暂无邮箱</p>';
})
const handleImageError = (e) => {
  e.target.src = 'https://example.com/default-avatar.png'; // 你的默认图地址
}
const formatData =computed(() => {
  return dayjs(userInfo.value.createdAt).format('YYYY-MM-DD HH:mm:ss');
})
const cancel = () => {
  formRef.value.resetFields(); // 重置表单
  dialogVisible.value = false;
  passwordt.value = '';
  ElMessage.info("已取消修改");
};
onMounted(()=>{
  userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
})
</script>
<style lang="less" scoped>
.d_content {
  width: 100%;
  display: flex;
  justify-content: center;
  .d_content_childer {
    width: 60%;
    .avatar {
      display: flex;
      width: 100%;
      height: 200px;
      justify-content: center;
    }
    .descriptions {
      width: 100%;
      margin-top: 20px;
    }
    .button {
      width: 100%;
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

</style>
